package com.lrs.java.j2se_self._example.countWords;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.lrs.java.j2se_self._example.countWords.PropertyMgr;

public class DBWordsCount extends WordsCount {
	Connection conn = null;
	Statement stmt = null;
	ResultSet rs = null;
	private String sql;
	
	public DBWordsCount(String sql) {
		this.sql = sql;
	}
	
	public String getText() {
		String sumWords = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = PropertyMgr.getProperty("url");
			String user = PropertyMgr.getProperty("user");
			String password = PropertyMgr.getProperty("password");
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
			/*
			 * 上面按照老师要求改用配置文件的方式读用户名和密码
			 * 下面是具体执行SQL语句的部分。用什么方式来设计更恰当。
			 * 比如说判断执行select和update语句，以及具体拿到那个字段的值（是不是通过传参来确定）
			 */
			rs = stmt.executeQuery(sql);
			while(rs.next()) {
				sumWords += rs.getString("id") + rs.getString("name");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(stmt != null) {
					stmt.close();
					stmt = null;
				}
				if(conn != null) {
					conn.close();
					conn = null;
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
		return sumWords;
	}
	
}
